/*
 * Copyright (c) 2001, 2002 Boris Pruessmann and others. All rights reserved.
 * This program and the accompanying materials are made available under the
 * terms of the Common Public License v0.5 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/cpl-v05.html
 * 
 * Contributors: Boris Pruessmann - Initial implementation.
 */
package net.sourceforge.perforce.api;

import java.text.MessageFormat;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

/**
 * @version $Revision: 488 $
 * @author <a href="mailto:bpruessmann@users.sourceforge.net>Boris
 *         Pruessmann</a>
 */
public class Policy {

  /** Stores an instance to the active ResourceBundle. */
  private static ResourceBundle bundle = null;

  /** Constructor for Policy. Private because Policy is a utility class. */
  private Policy() {
  }

  /**
   * Creates a NLS catalog for the given locale.
   * 
   * @param bundleName the name of the bundle.
   */
  public static void localize(String bundleName) {
    bundle = ResourceBundle.getBundle(bundleName);
  }

  /**
   * Lookup the message with the given ID in this catalog and bind its
   * substitution locations with the given string.
   * 
   * @param id the identifier of the message.
   * @param binding String that is bound to the message.
   * @return the complete message.
   */
  public static String bind(String id, String binding) {
    return bind(id, new String[] {binding});
  }

  /**
   * Lookup the message with the given ID in this catalog and bind its
   * substitution locations with the given strings.
   * 
   * @param id the identifier of the message.
   * @param binding1 String that is bound to the message.
   * @param binding2 String that is bound to the message.
   * @return the complete message.
   */
  public static String bind(String id, String binding1, String binding2) {
    return bind(id, new String[] {binding1, binding2});
  }

  /**
   * Gets a string from the resource bundle. We don't want to crash because of a
   * missing String.
   * 
   * @param key the identifier of the message.
   * @return the complete message; key if no message found.
   */
  public static String bind(String key) {
    try {
      return bundle.getString(key);
    } catch (MissingResourceException e) {
      return key;
    } catch (NullPointerException e) {
      return '!' + key + '!';
    }
  }

  /**
   * Gets a string from the resource bundle and binds it with the given
   * arguments.
   * 
   * @param key the identifier of the message.
   * @param args arguments to be bound to the message.
   * @return the complete message; key if no message found.
   */
  public static String bind(String key, Object[] args) {
    try {
      return MessageFormat.format(bind(key), args);
    } catch (MissingResourceException e) {
      return key;
    } catch (NullPointerException e) {
      return '!' + key + '!';
    }
  }
}
